import React from 'react';
import { connect } from 'react-redux';
import moment from 'moment';
import * as FilterStyle from './Filter.less';
import { DATE_FORMMATTER } from '../../../constants/datetime';

import { Subject, Grade, DateRange, Level3Navigator, SwitchDate } from '../components/dumb';
import { AreaSelector, CheckPanel } from '../components/smart';

import { CITY, COUNTY, SCHOOL, NONE } from '../../../constants/area';

import { switchSubView } from '../actions/level3Navigator';
import { selectedCity,
	     selectedCounty,
	     selectedSchool,
		 setDateRange,
	     selectedSubject,
	     selectedGrade,
	     /*获取年级数据*/
	 	 getGradeOptions,
	 	 getSubjectOptions,
	 	 /*获取地域数据*/
	 	 getCityOptions,
	 	 getCountyOptions,
	 	 getCountyOptionsSuccess,
	 	 getSchoolOptions,
	 	 getSchoolOptionsSuccess,
	 	 reset as filterReset } from '../actions/filter';	  

let now = moment().subtract(1, 'Days');;
let lastMonth = moment().subtract(1, 'M');
/**
 * [getAera 获取当前区域地域级别]
 * @param  {[type]} props [状态属性]
 * @return {[type]}       [description]
 */
function getAera(props) {
	let { filter }=props;
	if (filter.school.selectedItem.name){
		return SCHOOL;
	} else if (filter.county.selectedItem.name){
		return COUNTY;
	} else {
		return CITY;
	}
}

function mapStateToProps(state) {

	let { authentication, filter, level3Navigator } = state;

	return {
		authentication,
		filter,
		level3Navigator
	};
}

class Filter extends React.Component {
	static propTypes = {
		onSelectCity: React.PropTypes.func,
		onSelectCountry: React.PropTypes.func,
		onSelectSchool: React.PropTypes.func,
		onSelectSubject: React.PropTypes.func,
		onSelectGrade: React.PropTypes.func,
		onSelectStartDate: React.PropTypes.func,
		onSelectEndDate: React.PropTypes.func
	};
	
	constructor(props) {
		super(props);
	};

	lv3Items = [{
		ID: SCHOOL,
		label: '学校视图'
	}];
	//挂载时加载三级视图
	componentWillMount() {
		let { authentication, filter, level3Navigator, dispatch } = this.props;

		let right = parseInt(authentication.user.right);

		let countyView = {
			ID: COUNTY,
			label: '区县视图'
		}, cityView = {
			ID: CITY,
			label: '城市视图'
		};

		if (right == 2) {
			this.lv3Items.splice(0, 0, countyView);
		}
		// 市级
		else if (right == 3) {
			this.lv3Items.splice(0, 0, cityView, countyView);
		}
	}

	//设置开始时间
    handleSelectStartDate = (date) => {
		let { dispatch, filter, onFilterChange } = this.props;
		let { dateRange } = filter;
		dispatch(setDateRange([date,dateRange[1]]));

		onFilterChange && onFilterChange();
    };
    //设置截止时间
    handleSelectEndDate = (date) => {
		let { dispatch, filter, onFilterChange } = this.props;
		let { dateRange } = filter;
		dispatch(setDateRange([dateRange[0], date]));

		onFilterChange && onFilterChange();
    };

    /**
     * 选择科目和年级
     * @param  {[type]} Items [description]
     * @return {[type]}       [description]
     */
    handleSelectSubject = (items) => {
    	let { dispatch, onFilterChange } = this.props;
		dispatch(selectedSubject(items));

		onFilterChange && onFilterChange();
    };
    handleSelectGrade = (items) => {
    	let { dispatch, onFilterChange } = this.props;
    	dispatch(selectedGrade(items));

    	onFilterChange && onFilterChange();
    };

    /**
	 * 在对应导航栏下显示只显示相应的地域选择
	 * @param  {[type]} subview [用户主动切换三级视图传入的参数]
	 * @return {[type]}         [description]
	 */
	handleSwitchSubview = (subview) => {
		let { dispatch, filter, onFilterChange } = this.props;
		let { city, county, school } = filter;

		/*切换三级视图*/
		dispatch(switchSubView(subview));

		let selectedAction, mountSubAreaAction, 
			clearSubAreaSelectedActions = [], clearSubAreaActions = [];
		let defaultFirstOption;
		let loadDataRightNow = true;

		switch(subview) {
			case CITY:
				mountSubAreaAction = getCountyOptions(city.selectedItem.enum);
				clearSubAreaSelectedActions.push(selectedCounty);
				clearSubAreaSelectedActions.push(selectedSchool);
				clearSubAreaActions.push(getCountyOptionsSuccess);
				clearSubAreaActions.push(getSchoolOptionsSuccess);
				break;
			case COUNTY:
				defaultFirstOption = county.selectedItem;
				if (!defaultFirstOption.enum) {
					defaultFirstOption = county.options[0];
					selectedAction = selectedCounty(defaultFirstOption);
				}
				
				mountSubAreaAction = getSchoolOptions(defaultFirstOption.enum);
				clearSubAreaSelectedActions.push(selectedSchool);
				clearSubAreaActions.push(getSchoolOptionsSuccess);
				break;
			case SCHOOL:
				let { authentication } = this.props;
				let right = parseInt(authentication.user.right);
				if (right == 1)
					// 只有一个学校级别的用户角色是没有必要切视图的
					return;

				if (!school.selectedItem.enum && school.options.length) {
					defaultFirstOption = school.options[0];
					selectedAction = selectedSchool(defaultFirstOption);
				} else {
					loadDataRightNow = false;
					defaultFirstOption = county.options[0];
					selectedAction = selectedCounty(defaultFirstOption);

					mountSubAreaAction = getSchoolOptions(defaultFirstOption.enum, (options) => {
						if (options.length) {
							defaultFirstOption = options[0];
							dispatch(selectedSchool(defaultFirstOption));

							// this.getCurrentData();
							onFilterChange && onFilterChange();
						}
					});
				}
				break;
		}

		// 选中当前
		if (selectedAction)
			dispatch(selectedAction);

		// 清除下一级已选项
		if (clearSubAreaSelectedActions.length)
			clearSubAreaSelectedActions.forEach((item) => dispatch(item({})));

		// 清除下一级可选项
		if (clearSubAreaActions.length)
			clearSubAreaActions.forEach((item) =>dispatch(item([])));

		// 重新挂载下一级可选项
		if (mountSubAreaAction)
			dispatch(mountSubAreaAction);

		if (loadDataRightNow) {
			// this.getCurrentData();
			onFilterChange && onFilterChange();
		}
	};

	/**
     * 选择地域
     * @param  {string} key  行政地域级别键
     * @param  {object} area 地域
     */
    handleSelectedArea = (key, area) => {
    	let { dispatch, onFilterChange } = this.props;
    	let selectedAction, mountSubOptionsAction;

    	if (key == 'city') {
    		selectedAction = selectedCity(area);
    		mountSubOptionsAction = getCountyOptions(area.enum);

    		dispatch(selectedCounty({}));
    		dispatch(getCountyOptionsSuccess([]))
			dispatch(selectedSchool({}));
			dispatch(getSchoolOptionsSuccess([]));
    	} else if (key == 'county') {
    		selectedAction = selectedCounty(area);
    		mountSubOptionsAction = getSchoolOptions(area.enum);

    		dispatch(selectedSchool({}));
    		dispatch(getSchoolOptionsSuccess([]));
    	} else if (key == 'school') {
    		selectedAction = selectedSchool(area);
    	}

    	if (selectedAction) {
    		// 设置当前地域
    		dispatch(selectedAction);

    		if (mountSubOptionsAction) {
	    		// 获取下一级地域
	    		dispatch(mountSubOptionsAction);
	    	}

    		// 获取数据
    		// this.getCurrentData()
    		onFilterChange && onFilterChange();
    	}
    	this.handleSelectDate()
    };
    /**
	 * 切换近七天和近三十天
	 * @return {[type]} [description]
	 */
    handleSelectDate = (param) => {
		let { dispatch, onFilterChange } = this.props;
		let now = moment().subtract(1, 'days');
		let lastMonth=moment().subtract(1, 'M');
		let timespan = 30;
		if (param=='sevenDays')
		{
			lastMonth=moment().subtract(8, 'days');
			timespan = 7;
		}
		dispatch(setDateRange([lastMonth.format(DATE_FORMMATTER), now.format(DATE_FORMMATTER)]));
		onFilterChange && onFilterChange(timespan);
	}

	
	render() {
		/*获取state状态数据*/
		let { hasDateSelector, filter,level3Navigator, hasSwitchDate } = this.props;
		let { subject, grade, dateRange, city, county, school } = filter;
		let { subView } = level3Navigator;


		return (
			<div>
				<Level3Navigator onChange={this.handleSwitchSubview} selectedItem={subView} items={this.lv3Items} />
				<div className={FilterStyle.filter} >
					<AreaSelector currentSubView={subView} 
						city={city} 
						county={county} 
						school={school}>
						<CheckPanel  city={city} county={county} school={school}
							currentSubView={subView}
							onSelectCity={(area) => this.handleSelectedArea('city', area)}
							onSelectCounty={(area) => this.handleSelectedArea('county', area)}
							onSelectSchool={(area) => this.handleSelectedArea('school', area)}
							/>
					</AreaSelector>
					<Subject 
						options={subject.options} 
						selectedItems={subject.selectedItems}
						onSelectSubject={this.handleSelectSubject}/>
					<Grade 
						options={grade.options} 
						selectedItems={grade.selectedItems}
						onSelectGrade={this.handleSelectGrade} />
					{ hasDateSelector &&
						<div className='dateRange'>
							<span>时间 ：</span>
							<DateRange 
								date={lastMonth}
                    			maxDate={moment(dateRange[1]).subtract(1,'days')}
								primaryText={'开始日期:'+dateRange[0]}
								onDateChange = {this.handleSelectStartDate}
								 />
							<DateRange
								date={now}
								minDate={moment(dateRange[0])}
                    			maxDate={now}
								primaryText={'截止日期:'+dateRange[1]}
								onDateChange={this.handleSelectEndDate}
								/>
						</div>}
				</div>
				{ hasSwitchDate && <SwitchDate onSelectDate={this.handleSelectDate}/>}
			</div>
		)
	}
};


export default connect(mapStateToProps)(Filter);
